/**
 * 
 */
package com.vincent.action.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.vincent.action.basic.BasicAction;
import com.vincent.pojo.Credits;
import com.vincent.pojo.User;
import com.vincent.service.EnrollService;
import com.zhj.util.UTIL;

/**
 * 作者： Vincent 创建日期： 2014年4月20日 下午2:47:49 项目名字： MyForum
 */
@Component("enrollAction")
@Scope("prototype")
@ParentPackage("struts-default")
@Namespace("/")
public class EnrollAction extends BasicAction {

	private String userName;

	private String email;

	private String password;

	private String nickName;

	private String authCode;

	private String enrollFlag;

	private String emailAuthCode;

	private ByteArrayInputStream inputStream;
	@Resource
	private EnrollService enrollService;

	private static Logger logger = Logger.getLogger(EnrollAction.class);

	/**
	 * 跳转到注册页面
	 * 
	 * @return
	 */
	@Action(value = "enroll", results = { @Result(name = "ok", location = "/WEB-INF/web/enroll.jsp") })
	public String enroll() {
		return "ok";
	}

	/**
	 * 注册页面验证码
	 * 
	 * @return
	 * @throws IOException
	 */
	@Action(value = "enrollAuthCodeImage", results = { @Result(name = "authCodeImage", params = { "contentType",
			"image/jpeg", "inputName", "inputStream", "bufferSize", "2048" }, type = "stream") })
	public String enrollAuthCodeImage() throws IOException {
		String authCode = UTIL.getAuthCode(5);

		logger.info("[注册验证码：" + authCode + "]");

		session.setAttribute("enrollAuthCode", authCode);

		BufferedImage img = UTIL.getCodeImage(authCode);

		ByteArrayOutputStream output = new ByteArrayOutputStream();

		ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);

		ImageIO.write(img, "JPEG", imageOut);

		imageOut.close();

		ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());

		this.setInputStream(input);

		return "authCodeImage";
	}

	/**
	 * 注册验证
	 * 
	 * @return
	 */
	@Action(value = "enrollCheck", results = { @Result(name = "ok", type = "redirectAction", params = { "namespace",
			"/", "actionName", "enrollAuthCodeInput" }) })
	public String enrollCheck() {

		if (request.getMethod().equals("GET")) {

			try {

				response.sendRedirect("enroll.html?error=URLError");

			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(e);
			}
			return null;
		}

		if (!authCode.toLowerCase().equals(((String) (session.getAttribute("enrollAuthCode"))).toLowerCase())) {

			try {
				response.sendRedirect("enroll.html?error=authCodeError");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(e);
			}
			return null;
		}

		String returnString = enrollService.getEnrollCheck(userName, email);

		if (returnString != null) {
			try {
				response.sendRedirect("enroll.html?error=" + returnString);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(e);
			}
			return null;
		}

		String emailAuthCodeString = UTIL.getAuthCode(8);

		String emailContent = "欢迎您注册唐佳论坛！<br/>请妥善保留这封电子邮件. 您的帐号资料如下:<br/>用户名:" + userName + ",邮箱：" + email
				+ "。<br/>验证码：<span style='color:red;font-weight:bolder;'>" + emailAuthCodeString
				+ "</span><br/>请牢记您的密码， 因为密码经过了加密处理， 管理员也无法取得。如果您忘记了密码，可以在用户登录界面通过“找回密码”的链接，重置你的密码。";

		boolean b = UTIL.sendEmail("TangjiaForum", "123456abc", email, emailContent, "宇威科技");

		if (b) {

			User user = new User();
			
			user.setEmail(email);
			
			user.setNickName(nickName);
			
			user.setPwd(password);
			
			user.setUserName(userName);
			
			user.setGender("0");
			
			user.setAlterDate(new Date());
			
			user.setIcon("default.png");
			
			session.setAttribute("user", user);
			
			session.removeAttribute("enrollAuthCode");

			HashMap<String, Object> hMap = new HashMap<>();

			hMap.put("code", emailAuthCodeString);

			hMap.put("date", new Date().getTime());

			session.setAttribute("emailAuthCode", hMap);

			return "ok";
		}

		try {
			response.sendRedirect("enroll.html?error=emailSendError");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error(e);
		}
		return null;
	}

	@Action(value = "enrollAuthCodeInput", results = { @Result(name = "ok", location = "/WEB-INF/web/enrollAuthCodeInput.jsp") })
	public String enrollAuthCodeInput() {

		@SuppressWarnings("unchecked")
		HashMap<String, Object> hMap = (HashMap<String, Object>) session.getAttribute("emailAuthCode");

		if (hMap == null) {

			try {

				response.sendRedirect("enroll.html?error=emailAuthCodeLost");

			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(e);
			}

			return null;
		}

		long date = (long) hMap.get("date");

		long dateNow = new Date().getTime();

		long interval = dateNow - date;

		logger.info("[时间间隔：" + interval + "]");

		if (interval > 10 * 60 * 1000) {
			try {

				session.removeAttribute("emailAuthCode");

				response.sendRedirect("enroll.html?error=emailAuthCodeLost");

			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(e);
			}

			return null;
		}

		return "ok";

	}

	@Action(value = "enrollAuthCodeEmailCheck", results = { @Result(name = "ok",type = "redirectAction", params = { "namespace",
			"/", "actionName", "index" }) })
	public String enrollAuthCodeEmailChck() {

		@SuppressWarnings("unchecked")
		HashMap<String, Object> hMap = (HashMap<String, Object>) session.getAttribute("emailAuthCode");
		
		if (hMap == null) {

			try {

				response.sendRedirect("enroll.html?error=emailAuthCodeLost");

			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(e);
			}

			return null;
		}

		String sessionEmailAuthCodeString = (String) hMap.get("code");

		
		if (!sessionEmailAuthCodeString.toLowerCase().equals(emailAuthCode.toLowerCase())) {
			try {

				response.sendRedirect("enrollAuthCodeInput.html?error=emailAuthCodeError");

			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(e);
			}
			
			return null;
		}
		
		session.removeAttribute("emailAuthCode");
		
		User user = (User) session.getAttribute("user");
		
		user.setPwd(UTIL.MD5(user.getPwd()));
		
		Credits credits = new Credits();
		
		credits.setLabel("注册积分");
		
		credits.setNum(100);
		
		credits.setReleaseDate(user.getAlterDate());
		
		credits.setUser(user);
		
		List<Credits> list = new ArrayList<>();
		
		list.add(credits);
		
		user.setCreditses(list);
		
		enrollService.saveUser(user);
		
		user.setPwd("");
		
		return "ok";
	}

	public ByteArrayInputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(ByteArrayInputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getNickName() {
		return nickName;
	}

	public void setNickName(String nickName) {
		this.nickName = nickName;
	}

	public String getAuthCode() {
		return authCode;
	}

	public void setAuthCode(String authCode) {
		this.authCode = authCode;
	}

	public String getEnrollFlag() {
		return enrollFlag;
	}

	public void setEnrollFlag(String enrollFlag) {
		this.enrollFlag = enrollFlag;
	}

	public String getEmailAuthCode() {
		return emailAuthCode;
	}

	public void setEmailAuthCode(String emailAuthCode) {
		this.emailAuthCode = emailAuthCode;
	}

}
